package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @ClassName: DishFlavorController
 * @Author: xmc
 * @Date: 2022/8/17 16:05
 * @Version: 1.0
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){

        log.info("接收到：{}",dishDto);
        dishService.saveWithDishFlavor(dishDto);
        return R.success("保存成功");
    }
    @PutMapping
    @Transactional
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithDishFlavor(dishDto);
        return R.success("更新成功");

    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize, String name){
        //创建分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dtoInfo = new Page<>(page,pageSize);
        //添加分页条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper();
        wrapper.orderByDesc(Dish::getUpdateTime);
        wrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        dishService.page(pageInfo,wrapper);
        //通过对象拷贝，将pageinfo拷到dtoInfo,忽略records
        BeanUtils.copyProperties(pageInfo,dtoInfo,"records");
        //获取records
        List<Dish> records = pageInfo.getRecords();
        //遍历records,准备把categoryName赋上值
        List<DishDto> dtoRecords = records.stream().map((item) ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //获取category对象，目的是得到 categoryName
            Category category = categoryService.getById(item.getCategoryId());
            if (category!= null) {
                dishDto.setCategoryName(category.getName());

            }
            return dishDto;

        }).collect(Collectors.toList());
        dtoInfo.setRecords(dtoRecords);
        return R.success(dtoInfo);
    }

    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishWithDishFlavor = dishService.getByIdWithDishFlavor(id);
        return R.success(dishWithDishFlavor);
    }
    /**
     *
     *方法说明:删除和批量删除菜品和口味
     * @author xmc
     * @param ids
     * @return com.itheima.reggie.common.R<java.lang.String>
     * @date 2022/8/17 21:54
     */


    @DeleteMapping
    @Transactional
    public R<String> del(String ids){
        log.info(ids);
        String[] idInfos = ids.split(",");
        log.info(idInfos.toString());
        for (String idInfo : idInfos) {
            dishService.deleteWithDishFlavor(idInfo);
        }
//
        return R.success("删除成功");
    }

    @PostMapping("/status/{stus}")
    public R<String> changeStatus(String ids, @PathVariable String stus){

        log.info(stus);
        String[] idInfos = ids.split(",");
        log.info(idInfos.toString());
//        String[] split = request.getRequestURI().split("/");
//        log.info(split.toString());
//        String status = split[split.length - 1];
//        log.info(status);
        for (String idInfo : idInfos) {
            Dish dish = dishService.getById(idInfo);
            dish.setStatus(Integer.parseInt(stus));
            dishService.updateById(dish);
        }
        return R.success("停售成功");
    }
/**
 *
 *方法说明:根据条件查询菜品信息
 * @author xmc
 * @param dish
 * @return com.itheima.reggie.common.R<java.util.List<com.itheima.reggie.entity.Dish>>
 * @date 2022/8/18 6:58
 */

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        log.info("接收到:{}",dish);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        wrapper.eq(Dish::getStatus,1);
        wrapper.orderByDesc(Dish::getSort).orderByAsc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(wrapper);
        List<DishDto> dishDtos = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //获取category对象，目的是得到 categoryName
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            //根据菜品id查询菜品关联的口味信息
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,item.getId());
            List<DishFlavor> list1 = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(list1);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtos);
    }
}
